
import datolib.*;

/**
* A class to represent an instance of a Java application running from Datolite 
*
* @file DatoliteInstance.java
* @author Blair Harris 
*/
public class DatoliteInstance {
	
	private String applicationID;
	private PlatformImplementation platform;
	private Class<?> clas;
	private Object instance;
	
	/**
	* Default constructor, does nothing
	*/
	public DatoliteInstance() {
		this.applicationID = null;
		this.platform = null;
		this.clas = null;
		this.instance = null;
	}
	
	public DatoliteInstance(String id, PlatformImplementation pi) {
		this.applicationID = id;
		this.platform = pi;
		
		DatoliteClassLoader loader = new DatoliteClassLoader();

		try {
			this.clas = loader.loadClass(this.platform.classFile());
		} catch (Exception e) {
			this.clas = null;
		}
	}

	public String getApplicationID(){
		return this.applicationID;
	}
	
	public String getCimlFile() {
		return this.platform.cimlFile();
	}
	
	public String getUipFile() {
		return this.applicationID + ".uip";
	}
	
	public boolean buildInstance() {
		try {
			this.instance = this.clas.newInstance();
			
			if (this.instance == null) {
				return false;
			}
			
			return true;
			
		}catch (Exception e) {
			return false;
		}
	}
	
	/**
	* Invoke the init() method to get the instance running
	*
	* @return 
	*   True if the init() method was successfully called other wise false
	*/	
	public boolean initApplication(TcpGateway socket) {
		try { 
			this.clas.getMethod("init", ClientInterface.class).invoke(this.instance, new ClientInterface(socket));
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean executeEvent(TevMessage tev) {
		try {
			this.clas.getMethod(tev.function(), tev.getClasses()).invoke(this.instance, tev.getObjects());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
